<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="obj in cateList" :key="obj.id" :label="obj.cate_name" :value="obj.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="choseFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题">
          <template #default="scope">
            <el-link type="primary" @click="showDetailFn(scope.row.id)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template #default="scope">
            <span>{{$formatDate(scope.row.pub_date)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作"></el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn" :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size.sync="q.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 发表文章的 Dialog 对话框 -->
    <el-dialog title="发表文章" :visible.sync="detailVisible" fullscreen :before-close="handleClose" @close="dialogCloseFn">
      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option v-for="obj in cateList" :key="obj.id" :label="obj.cate_name" :value="obj.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content" @blur="contentChangeFn"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticleFn('草稿')">存为草稿</el-button>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" prop="cover-img " ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="changeCoverFn" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="selCoverFn">+ 选择封面</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
  getArtCateListAPI,
  uploadArticleAPI,
  getArtListAPI,
  getArtDetailAPI,
} from '@/api/index.js'
import imgObj from '../../assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1, //默认请求第一页的数据
        pagesize: 2, //每页显示的数据数量
        cate_id: '', //列表id
        state: '', //列表状态
      },
      //控制对话框的出现和隐藏
      pubDialogVisible: false,
      detailVisible: false,
      pubForm: {
        // 表单的数据对象
        title: '', //文章标题
        cate_id: '', //文章分类id
        content: '', //文章内容
        cover_img: null, //图片的路径信息
        state: '', //发布状态（已发布或者草稿）
      },
      pubFormRules: {
        // 表单的验证规则对象
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur',
          },
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
        ],
        cover_img: [{ required: true, message: '请选择封面', trigger: 'blur' }],
      },
      cateList: [],
      artList: [], //保存文章类表
      total: 0, //文章的总数
      artDetail: {},
    }
  },
  methods: {
    //获取所有的文章列表
    async getArticleListFn() {
      const { data: res } = await getArtListAPI(this.q)
      this.artList = res.data
      this.total = res.total
    },
    //对话框关闭前的会掉
    // 对话框关闭前的回调
    async handleClose(done) {
      // 询问用户是否确认关闭对
      const confirmResult = await this.$confirm(
        '此操作将导致文章信息丢失, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 取消了关闭-阻止住, 什么都不干
      if (confirmResult === 'cancel') return
      // 确认关闭
      done()
    }, //done调用就会关闭
    showPubDialogFn() {
      this.pubDialogVisible = true
    },
    //获取所有分类
    async getCateListFn() {
      const { data: res } = await getArtCateListAPI()
      this.cateList = res.data
      console.log(this.cateList)
    },
    //选择封面的点击事件
    selCoverFn() {
      this.$refs.iptFileRef.click()
    },
    //用户选择了封面文件
    changeCoverFn(e) {
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', imgObj)
      } else {
        // 用户选择了封面
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
      this.$refs.pubFormRef.validateField('cover_img')
    },
    //表单里面点击发布 存为按钮 的点击事件 准备调用后端接口
    pubArticleFn(str) {
      //str要么是已发布或者是草稿
      this.pubForm.state = str
      //兜底验证
      this.$refs.pubFormRef.validate(async (valid) => {
        if (valid) {
          console.log(this.pubForm)
          let fd = new FormData() //FormData专门的表单容器
          fd.append('title', this.pubForm.titile)
          fd.append('cate_id', this.pubForm.cate_id)
          fd.append('content', this.pubForm.content)
          fd.append('cover_img', this.pubForm.cover_img)
          fd.append('state', this.pubForm.state)
          const { data: res } = await uploadArticleAPI(fd)
          if (res.code !== 0) return this.$message.error('发布文章失败！')
          this.$message.success('发布文章成功！')
          //关闭对话框
          this.pubDialogVisible = false
          //刷新列表
          this.getArticleListFn()
        } else {
          return false //阻止默认行为 按钮有默认提交行为
        }
      })
    },
    //富文本编辑器内容改变了触发词事件方法
    contentChangeFn() {
      this.$refs.pubFormRef.validateField('content')
    },
    //新增文章对话框关闭时清空表单
    dialogCloseFn() {
      this.$refs.pubFormRef.resetFields()

      this.$refs.imgRef.setAttribute('src', imgObj)
    },
    //当每页显示的条数改变时候触发
    handleSizeChangeFn(newSize) {
      this.q.pagesize = newSize
      //问题先点击最后一个页码，切换每页条数总数不够只能分到2
      this.q.pagenum = 1
      this.getArticleListFn()
    },
    handleCurrentChangeFn(newCurrent) {
      this.q.pagenum = newCurrent
      this.getArticleListFn()
    },

    //筛选按钮的点击事件
    choseFn() {
      //目的当有了筛选的条件，
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.getArticleListFn()
    },
    //充值按钮的点击事件
    resetFn() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: '',
      }
      this.getArticleListFn()
    },
  },
  created() {
    //请求分类的数据
    this.getCateListFn()
    //调用请求文章列表的数据
    this.getArticleListFn()
  },
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
::v-deep .ql-editor {
  min-height: 300px;
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
